package com.q3d.demo.common.lib.logger;

import com.q3d.demo.common.lib.logger.runner.LogRunner;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;

/**
 * 日志统一加前缀
 * 
 * @author 叶湘 ( weixin:yexiang841, email:yexiang841@qq.com )
 */
public class LogPreConverter extends ClassicConverter {

    @Override
    public String convert(ILoggingEvent event) {
        StringBuffer stringBuilder = new StringBuffer();
        // 从线程缓存读取服务名
        String applicationNameAndServerPort = LogRunner.threadLocalName.get();
        if (applicationNameAndServerPort != null) {
            stringBuilder.append(applicationNameAndServerPort);
        }
        // 从线程缓存读取开始时间
        Long startTime = LogRunner.threadLocalTime.get();
        // 如果能取到时间则拼上
        if (startTime != null) {
            stringBuilder.append(" start: " + (startTime.toString()));
            long currentTime = System.currentTimeMillis();
            stringBuilder.append(" cost: " + (currentTime - startTime.longValue()) + "ms");
        }
        return stringBuilder.toString();
    }

}